<template>
  <div class="rich-text-editor-vue" ref="editorEl">

  </div>
</template>
<script name="RichTextEditor" setup>
import  'wangEditor';
import {onMounted, ref, watch} from 'vue'

const editorEl = ref(null)
const props = defineProps({
  modelValue: String,
  type: {
    type: String,
    default: 'html' // html, text
  },
  height: {
    type: Number,
    default: 80
  },
  cache: {
    type: Boolean,
    default: false // 是否开启本地存储
  }
})

const emit = defineEmits(['update:modelValue', 'change','init'])
let editor = null
const isHtml=props.type === 'html';
let tempV
onMounted(() => {
  const el = editorEl.value
  editor = new wangEditor(el);
  // 开启图片复制
  editor.config.uploadImgShowBase64 = true;
  editor.config.onchange = (html) => {
    let text = editor.txt.text();
    if (props.cache) {
      localStorage.editorCache = html;
    }
    let value = isHtml ? html : text;
    tempV=value
    emit('update:modelValue', value);
    emit('change', html, text);
  };
  if (props.height) {
    editor.config.height = props.height
  } else {
    editor.config.height = 60
  }
  emit('init',editor)
  editor.create();
  let html = props.modelValue
  if (!html && props.cache) {
    html = localStorage.editorCache;
  }

  if (html) editor.txt.html(html);

})
watch(() => props.modelValue, (v, perv) => {
  if (editor){
    if(tempV!=v){
      tempV=v
      editor.txt.html(v)
    }
  }
})
</script>
